package com.ebai.product.management.service.system;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ebai.product.management.base.cache.service.MessageCacheImpl;
import com.ebai.product.management.base.utils.SysCode;
import com.ebai.product.management.model.entity.Dept;
import com.ebai.product.management.model.entity.User;
import com.ebai.product.management.repository.system.DeptRepository;

import net.sf.json.JSONArray;

/**
 * 系统 部门管理 业务处理类
 * @author mgli
 *
 */
@Service
public class DeptService {

	@Autowired
	private DeptRepository deptRepository;
	
	/**
     * 依据条件查询分页数据
     * @param page
     * @param size
     * @param authQuery
     * @return
     */
    public Page<Dept> queryPage(Integer page, Integer size, final Dept deptQuery) {
        Pageable pageable = PageRequest.of(page-1, size, Sort.Direction.DESC, "createTime");
        Page<Dept> rolePage = this.deptRepository.findAll(new Specification<Dept>(){
            public Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                
                // 过滤部门名称
                if ( StringUtils.isNotBlank(deptQuery.getDeptName()) ){
                    list.add(criteriaBuilder.like(root.get("deptName").as(String.class), "%"+ deptQuery.getDeptName() +"%"));
                }
                // 过滤是否启用
                if ( StringUtils.isNotBlank(deptQuery.getIsEnable()) ){
                    list.add(criteriaBuilder.equal(root.get("ssEnable").as(String.class), SysCode.DICT_TYSF.YES));
                }

                // 过滤创建时间条件
                if ( StringUtils.isNotBlank(deptQuery.getCreateTimeBetween()) ){
                    String[] createTime = deptQuery.getCreateTimeBetween().split(" ~ ");
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Timestamp.class), Timestamp.valueOf(createTime[0] + " 00:00:00")));
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(Timestamp.class), Timestamp.valueOf(createTime[1] + " 23:59:59")));
                }
                list.add(criteriaBuilder.equal(root.get("isDelete").as(String.class), SysCode.DICT_TYSF.NO));
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, pageable);

        return rolePage;
    }
    
    public Map<String, Object> selectDeptList() {
		Map<String, Object> result = new HashMap<String, Object>();
        result.put("is", false);
        
        try {
        	List<Dept> deptList = this.deptRepository.selectDeptList();
        	JSONArray jsonArray = JSONArray.fromObject(deptList);
    		
    		result.put("code", "0");
    		result.put("count", deptList.size());
    		result.put("data", jsonArray);
    		result.put("is", true);
    		result.put("msg", "");
    		result.put("tip", "获取数据成功");
		} catch (Exception e) {
			// TODO: handle exception
    		result.put("msg", "获取数据失败");
			e.printStackTrace();
		}
        
		return result;
	}
    
    /**
     * 保存或更新表单数据
     * @param entity
     * @return
     */
    public Map<String, Object> saveData(Dept oldEntity, User sessionUser) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
        	Dept newEntity = null;
            if (StringUtils.isBlank(oldEntity.getPid())) {
            	newEntity = new Dept();
            	BeanUtils.copyProperties(oldEntity, newEntity);
            	newEntity.setIsDelete(SysCode.DICT_TYSF.NO);
            	newEntity.setCreator(sessionUser.getLoginName());
            	newEntity.setLastUpdateRegenerator(sessionUser.getLoginName());
            }
            else {
            	newEntity = this.deptRepository.findByPid(oldEntity.getPid());
            	oldEntity.setCreateTime(newEntity.getCreateTime());
            	oldEntity.setCreator(newEntity.getCreator());
            	oldEntity.setIsDelete(newEntity.getIsDelete());
                BeanUtils.copyProperties(oldEntity, newEntity);
                oldEntity.setLastUpdateRegenerator(sessionUser.getLoginName());
            }
            this.deptRepository.save(newEntity);

            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Failure") + e.getMessage());
        }

        return result;
    }

    /**
     * 依据主键执行逻辑删除
     * @param ids
     * @return
     */
    public Map<String, Object> dropData(String dataPid) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
            if (StringUtils.isNotBlank(dataPid)) {
            	List<Dept> childListDept = this.deptRepository.selectDeptByParentId(dataPid);
            	if (null != childListDept && childListDept.size()>0) {
            		result.put("msg", "存在下级部门,不允许删除");
            		return result;
            	}
                this.deptRepository.deleteById(dataPid);
            }

            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.DeleteData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.DeleteData.Message.Failure") + e.getMessage());
        }

        return result;
    }
    
    public List<Map<String, Object>> selectDeptTree() {
        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
        List<Dept> deptList = deptRepository.selectDeptList();

        for (Dept dept : deptList) {
            if (StringUtils.equals(dept.getParentId(), SysCode.DICT_TYSF.NO) 
            		&& StringUtils.equals(dept.getIsEnable(), SysCode.DICT_TYSF.YES)) {
                Map<String, Object> deptMap = new HashMap<String, Object>();
                deptMap.put("id", dept.getPid());
                deptMap.put("name", dept.getDeptName());
                deptMap.put("open", true);
                addDeptChild(deptMap, deptList);
                
                trees.add(deptMap);
            }
        }
        
        JSONArray jsonArray = JSONArray.fromObject(trees);
        return trees;
    }
    
    public void addDeptChild(Map<String, Object> parentDeptMap, List<Dept> deptList) {
    	List<Map<String, Object>> childTrees = new ArrayList<Map<String, Object>>();
    	for (Dept deptChild : deptList) {
			if (StringUtils.equals(parentDeptMap.get("id").toString(), deptChild.getParentId())) {
				Map<String, Object> childDeptMap = new HashMap<String, Object>();
				childDeptMap.put("id", deptChild.getPid());
				childDeptMap.put("name", deptChild.getDeptName());
				if (hasChild(childDeptMap, deptList)) {
					childDeptMap.put("open", true);
					addDeptChild(childDeptMap, deptList);
				}
				else {
					childDeptMap.put("open", false);
				}
				
				childTrees.add(childDeptMap);
			}
		}
		parentDeptMap.put("children", childTrees);
    }
    
    public boolean hasChild(Map<String, Object> parentDeptMap, List<Dept> deptList) {
    	for (Dept deptChild : deptList) {
    		if (StringUtils.equals(parentDeptMap.get("id").toString(), deptChild.getParentId())) {
    			return true;
    		}
		}
    	
    	return false;
    }
}
